package com.hbnu.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.mapper.AwardMapper;
import com.hbnu.system.mapper.AwardQualificationMapper;
import com.hbnu.system.model.context.BaseContext;
import com.hbnu.system.model.dto.AwardDTO;
import com.hbnu.system.model.entity.Award;
import com.hbnu.system.model.entity.Award_Qualification;
import com.hbnu.system.model.entity.Awardauthor;
import com.hbnu.system.model.entity.User;
import com.hbnu.system.service.*;
import com.hbnu.system.utils.CheckRoleUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Objects;

@Service
public class AwardQualificationServiceImpl extends ServiceImpl<AwardQualificationMapper, Award_Qualification> implements IAwardQualificationService {
   @Autowired
   private IAwardService iAwardService;

   @Autowired
   private IAwardTypeService iAwardTypeService;

   @Autowired
   private IAwardType2Service iAwardType2Service;

    @Autowired
    private CheckRoleUtil checkRoleUtil;

   @Autowired
   private AwardMapper awardMapper;
   @Autowired
   private IUserService iUserService;
   
   @Autowired
   private IAwardauthorService iAwardauthorService;

   @Autowired
   private IAwardQualificationService iAwardQualificationService;

    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.00");


    @Transactional
    @Override
    public boolean addAward_Qualification(Award_Qualification award_qualification) {
        Award p1=iAwardService.getAward(award_qualification.getAwardID());
        checkRoleUtil.checkPermissionAchievement(p1.getStatus());
        //检查是否已经存在量化
        Award_Qualification existingQualification = iAwardQualificationService.getOne(Wrappers.lambdaQuery(Award_Qualification.class)
                .eq(Award_Qualification::getAwardID, award_qualification.getAwardID()));
        if (Objects.nonNull(existingQualification)) {
            throw new BaseException("已存在量化分数，不可重复添加");
        }

        Award award=iAwardService.getAward(award_qualification.getAwardID());
        String scoreStr = DECIMAL_FORMAT.format(award_qualification.getFinalValue());
        award.setScore(Float.parseFloat(scoreStr));
        System.out.println("award="+award);
        iAwardService.updateById(award);
        baseMapper.insert(award_qualification);
        List<Awardauthor> awardauthorList = iAwardauthorService.listAuthor(award.getAwardID());

        if(!CollectionUtils.isEmpty(awardauthorList)){
            for (Awardauthor author : awardauthorList) {
                iAwardauthorService.updateAwardAuthor(author);
            }
        }

        return true;
    }

    @Override
    @Transactional
    public boolean deleteAward_Qualification(String AwardQualificationID) {
        Award_Qualification award_qualification = iAwardQualificationService.getById(AwardQualificationID);
        Award p1=iAwardService.getAward(award_qualification.getAwardID());
//        System.out.println(p1);
        checkRoleUtil.checkPermissionAchievement(p1.getStatus());
//        Award_Qualification award_qualification = baseMapper.selectOne(Wrappers.lambdaQuery(Award_Qualification.class)
//                .eq(Award_Qualification::getAwardQualificationID, AwardQualificationID));

        if (Objects.isNull(award_qualification)){
            throw new BaseException("量化编号有误");
        }

        AwardDTO awarddto = iAwardService.getAwardDTOById(award_qualification.getAwardID());
        awarddto.setScore(0);

        Award award = new Award();
        BeanUtils.copyProperties(awarddto,award);
        iAwardService.updateById(award);
        baseMapper.deleteById(AwardQualificationID);

        List<Awardauthor> awardauthorList = iAwardauthorService.listAuthor(award.getAwardID());

        if(!CollectionUtils.isEmpty(awardauthorList)){
            for (Awardauthor author : awardauthorList) {
                iAwardauthorService.updateAwardAuthor(author);
            }
        }
        return true;
    }

    @Override
    public List<Award_Qualification> getOneAward_Qualification(String AwardID) {
        Award award = iAwardService.getAward(AwardID);
        if(Objects.isNull(award)){
            throw new BaseException("获奖编号有误!");
        }

        List<Award_Qualification> award_qualifications = baseMapper.selectList(Wrappers.lambdaQuery(Award_Qualification.class)
                .eq(Award_Qualification::getAwardID, AwardID));

        return award_qualifications;
    }

    /**
     * 更新获奖分
     * @param awardQualification
     * @return
     */
    @Override
    public boolean upAwardScore(Award_Qualification awardQualification) {
        Award p1=iAwardService.getAward(awardQualification.getAwardID());
        checkRoleUtil.checkPermissionAchievement(p1.getStatus());
        Award_Qualification a = baseMapper.selectOne(Wrappers.lambdaQuery(Award_Qualification.class)
                .eq(Award_Qualification::getAwardQualificationID, awardQualification.getAwardQualificationID()));
        a.setFinalValue(awardQualification.getFinalValue());

        Award award = awardMapper.selectOne(Wrappers.lambdaQuery(Award.class)
                .eq(Award::getAwardID, awardQualification.getAwardID()));

        String scoreStr = DECIMAL_FORMAT.format(awardQualification.getFinalValue());
        award.setScore(Float.parseFloat(scoreStr));
        iAwardService.updateAward(award);

        String Pscore = "0.00";
        // 9. 修改著作作者的个人得分
        String awardid=awardQualification.getAwardID();
        List<Awardauthor> awardauthorList = iAwardauthorService.listAuthor(awardid);
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (awardauthorList != null && !awardauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (awardauthorList.size() == 1) {
                Awardauthor soleAuthor = awardauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Awardauthor author : awardauthorList) {
                    iAwardauthorService.updateAwardAuthor(author);
                }
            }
        }

        return baseMapper.updateById(a) == 1;
    }
}
